package com.yashi.service.impl;

import java.security.SecureRandom;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.springframework.stereotype.Service;

import com.yashi.dao.TbAdminMapper;
import com.yashi.dao.TbUserMapper;
import com.yashi.entity.TbAdmin;
import com.yashi.entity.TbUser;
import com.yashi.service.AdminService;
import com.yashi.utils.YSUtils;

@Service
public class AdminServiceImpl implements AdminService {

	@Resource
	private TbAdminMapper adminDao;
	
	@Resource
	private TbUserMapper userDao;
	
	/**
	 * 密码加密
	 */
	private static final byte[] DES_KEY = { 21, 1, -110, 82, -32, -85, -128, -65 };
    @SuppressWarnings("restriction")
    public static String encryptBasedDes(String data) {
        String encryptedData = null;
        try {
            // DES算法要求有一个可信  任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            // 加密，并把字节数组编码成字符串
            encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            // log.error("加密错误，错误信息：", e);
            throw new RuntimeException("加密错误，错误信息：", e);
        }
        return encryptedData;
    }
    /**
     * 解密
     * @param cryptData
     * @return
     */
    @SuppressWarnings("restriction")
    public static String decryptBasedDes(String cryptData) {
        String decryptedData = null;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            // 把字符串进行解码，解码为为字节数组，并解密
            decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
        } catch (Exception e) {
            throw new RuntimeException("解密错误，错误信息：", e);
        }
        return decryptedData;
    }
	
	
	@SuppressWarnings("unused")
	@Override
	public TbAdmin findAdminByName(TbAdmin admin) throws Exception {
		//接收前台传过来的用户名和密码
		String adminName = admin.getAdminName();
		String password = admin.getPassword();
		//查询数据库
		TbAdmin findAdmin = adminDao.findAdminByName(adminName);
		String adminPass = findAdmin.getPassword();
		if(findAdmin==null){
			throw new Exception("用户名或密码错误");
		}else{
			if(password.equals(decryptBasedDes(adminPass))){
				System.out.println("web端登录成功");
				return findAdmin;
			}else{
				throw new Exception("用户名或密码错误");
			}
		}
	}
	@Override
	public TbAdmin addAdmin(TbAdmin admin,String userId) {
		TbUser user = userDao.selectByPrimaryKey(userId);
		admin.setId(YSUtils.getUUID());
		admin.setAdminName(user.getUsername());
		admin.setPassword(user.getPassword());
		admin.setPosition("管理员");
		admin.setPhone(user.getPhone());
		admin.setCreateDate(YSUtils.getCurrentTime());
		admin.setDelFlag("0");
		adminDao.insertSelective(admin);
		System.out.println("管理员设置成功");
		return admin;
	}

}
